// 加载express模块
const express = require('express');
const md5 = require('md5');

// 引入线程池,参数解构 pool1:kc pool2:words pool3:46zt 
const { pool1, pool2, pool3 } = require('../kc_pool.js')

//创建路由器 
const r = express.Router()

//转换当前时间为datetime格式   精确到minute
var formatDateTime = function (date) {  
    var y = date.getFullYear();  
    var m = date.getMonth() + 1;  
    m = m < 10 ? ('0' + m) : m;  
    var d = date.getDate();  
    d = d < 10 ? ('0' + d) : d;  
    var h = date.getHours();  
    var minute = date.getMinutes();  
    minute = minute < 10 ? ('0' + minute) : minute;  
    // var seconds=date.getSeconds();
	// seconds= seconds<10 ? ('0'+seconds) :seconds;
	var sjc = y + '/' + m + '/' + d+' '+h+':'+minute;
	//打印
	// console.log(sjc)
    return sjc;  
};  


//封装盐加密

var sMD5 = function (pwd,phone,time){
	// 盐
	let slat=phone;
	// 第一次加密
	let pass=md5(pwd);
	// 盐加密
	let pst=md5(pass+slat);
	//加入时间戳 精分
	let upwd=pst+time
	return  upwd
}
//随机生成32个字母
// function getPass(len)
// {
// var tmpCh = "";
// for(var i = 0; i < len; i++)
// {
// tmpCh += String.fromCharCode(Math.floor( Math.random() * 26) + "a".charCodeAt(0));
// }
// return tmpCh;
// }

// 测试接口
r.get("/test", (req, res) => {

	console.log("已接受");

	res.send("服务器已接到请求")
})

// 1.用户登录接口 
r.post('/login', (req, res, next) => {
	console.log('登录请求')
	//	手机号
	let uPhone = req.body.uPhone;

	//	密码
	var uPwd = req.body.uPwd;

	// SQL语句 kc库 user表
	//查询盐
	let sql1='SELECT uTime FROM user where uPhone = ?';

	//执行查询语句1
	pool1.query(sql1,[uPhone],(error,results)=>{

		if(error) next(error);

		//获取user库的时间戳
		let time=formatDateTime(results[0].uTime) ;
		// console.log('登陆时间戳:'+time)
		//对用户发来的密码盐加密
		let userPwd = sMD5(uPwd,uPhone,time);
		// console.log('登陆盐密码:'+userPwd)
		//通过userPwd和uPhone进行查询
		// SQL语句 kc库 user表
		let sql2 = 'SELECT uId,uName,uPhone,uCountry,uAvatar FROM user WHERE uPhone=? AND uPwd=?';

		// 执行查询语句2
		pool1.query(sql2, [uPhone,userPwd], (error, results) => {

		// 报错,next中间件抛出
		if (error) {

			next(error);

			return
		}
		if (results.length == 0) { //登录失败

			res.send({ message: '用户名或密码错误', code: 201 });

		} else {                 //登录成功

			res.send({ message: '登录成功', code: 200, result: results });
		}
	});
		
	})


	// SQL语句 kc库 user表
	// let sql = 'SELECT uId,uName,uPhone,uCountry,uAvatar FROM user WHERE uPhone=? AND uPwd=?';

	//	执行查询语句
	// pool1.query(sql, [uPhone, slatPwd], (error, results) => {

	// 	// 报错,next中间件抛出
	// 	if (error) {

	// 		next(error);

	// 		return
	// 	}
	// 	if (results.length == 0) { //登录失败

	// 		res.send({ message: '用户名或密码错误', code: 201 });

	// 	} else {                 //登录成功

	// 		res.send({ message: '登录成功', code: 200, result: results });
	// 	}
	// });

});


//2.用户注册接口
r.post('/reg', (req, res, next) => {
	console.log('reg验证中间传过来的')
	//	昵称
	let uName = req.body.uName;

	//	密码
	let uPwd = req.body.uPwd;

	//获取时间戳 精分
	let date = new Date();
	
	//获取time 精分
	let time = formatDateTime(date);
	// console.log('注册时间戳:'+time)
	//	手机号
	let uPhone = req.body.uPhone;

	//调用MD5盐方法
	let userPwd = sMD5(uPwd,uPhone,time);
	//打印
	// console.log('注册盐加密码: '+ userPwd);

	//	国家
	let uCountry = req.body.uCountry;

	// 头像链接
	if (req.body.uAvatar == undefined || req.body.uAvatar == '') {

		var uAvatar = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201610%2F04%2F20161004161302_VreQT.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632495062&t=cbe43f9bdd6ddfdaaa3c9bda6421d73d";

	} else {

		var uAvatar = req.body.uAvatar

	}
	// 非空验证
	if (!(uName && uPwd && uPhone && uCountry && uAvatar)) {
		if (!uName) {
			console.log('用户名不能为空')
			res.send({ message: '用户名不能为空', code: 203 });
		} else if (!uPwd) {
			console.log('密码不能为空')
			res.send({ message: '密码不能为空', code: 203 });
		} else if (!uPhone) {
			console.log('手机号不能为空')
			res.send({ message: '手机号不能为空', code: 203 });
		} else if (!uCountry) {
			console.log('国籍不能为空')
			res.send({ message: '国籍不能为空', code: 203 });
		} else {
			console.log('用户头像链接不能为空')
			res.send({ message: '用户头像链接不能为空', code: 203 });
		}
	} else {
		//以uPhone为条件进行查找操作，以保证用户名的唯一性 user表
		var sql = 'SELECT uPhone AS Phone,uName AS Name FROM user WHERE uPhone=? or uName=?';
		// SQL语句 kc库 user表
		pool1.query(sql, [uPhone, uName], (error, results) => {

			if (error) {

				next(error);

				return
			}
			console.log(results);
			// 获取查询到数量  
			if (results[0]) {
				let Phone = results[0].Phone;

				let Name = results[0].Name;

				if (Phone == uPhone || Name == uName) {// 判断手机号码或昵称是否存在

					Phone == uPhone ? res.send({ message: '手机号已注册', code: 201 }) : res.send({ message: '昵称已注册', code: 201 })
				}


			} else {
				// 将用户的相关信息插入到数据表
				sql = 'INSERT user(uName,uPwd,uPhone,uCountry,uAvatar,uTime) VALUES(?,?,?,?,?,?)';

				pool1.query(sql, [uName,userPwd, uPhone, uCountry,
					uAvatar,time], (error, results) => {

						if (error) {

							next(error);

							return
						}
						res.send({ message: '注册成功', code: 200 });
					})
			}
		});
	}


});


// 3.首页查询课程接口
r.get('/course', (req, res, next) => {

	// SQL语句 kc库 course表
	pool1.query('select * from course', (error, results) => {

		// 报错,next中间件抛出
		if (error) {

			next(error);

			return
		}
		//查询成功
		res.send({ message: '查询到课程', code: 200, result: results });

	});

});


// 4.获取收货人信息
r.get('/address', (req, res, next) => {

	// 昵称
	let aName = req.query.aName;

	//用户uId
	let aUid = req.query.aUid;

	// SQL语句 kc库 adds表
	let sql = 'select * from adds where aName=? or aUid=?';

	pool1.query(sql, [aName, aUid], (error, results) => {

		if (error) {

			next(error);

			return
		}

		if (results.length == 0) {

			res.send({ message: '尚未填写收货地址', code: 201 })
		} else {
			res.send({
				message: '查询到已有收货地址', code: 200, result: results
			})
		}
	})
});

// 4.1 aId获取唯一收货人信息
r.get('/addonly', (req, res, next) => {

	// 地址aId
	let aId = req.query.aId;
	console.log('获取aId:' + aId)
	// SQL语句 kc库 adds表
	let sql = 'select * from adds where aId = ?';

	pool1.query(sql, [aId], (error, results) => {

		if (error) {

			next(error);

			return
		}

		if (results.length == 0) {

			res.send({ message: '尚未填写收货地址', code: 201 })
		} else {
			res.send({
				message: `查询到${aId}号收货地址`, code: 200, result: results
			})
		}
	})
});

// 5.删除收货人信息
r.post("/addel", (req, res, next) => {

	//昵称
	let aId = req.body.aId;

	//SQL语句 
	let sql = 'delete from adds where aId=?'

	pool1.query(sql, [aId], (error, results) => {

		if (error) {

			next(error);

			return
		}

		if (results.affectedRows > 0) {
			res.send({ message: aId + '号收货地址已删除', code: 200 })
		} else {
			res.send({ message: '尚未添加收货地址', code: 201 })
		}
	})
})


// 6.修改收货人信息
r.post("/addmod", (req, res, next) => {
	// 昵称
	let aId = req.body.aId;
	// 收件人电话
	let aPhone = req.body.aPhone;
	// 收件人姓名
	let aDsser = req.body.aDsser;
	// 收件地址
	let aDs = req.body.aDs;

	// SQL语句
	var sql = "update adds set aPhone=?,aDsser=?,aDs=? where aId=?";
	// 修改
	pool1.query(sql, [aPhone, aDsser, aDs, aId], (error, results) => {
		if (error) {

			next(error)

		}
		if (results.affectedRows > 0) {
			res.send({ message: "收货地址修改成功", code: 200 })
		} else {
			res.send({ message: "尚未添加收货地址", code: 201 })
		}
	})
});

// 7.添加收货人信息
r.post("/addto", (req, res, next) => {
	//用户uId
	let aUid = req.body.aUid;
	// 昵称
	let aName = req.body.aName;
	// 收件人电话
	let aPhone = req.body.aPhone;
	// 收件人姓名
	let aDsser = req.body.aDsser;
	// 收件地址
	let aDs = req.body.aDs;

	if (!(aUid && aName)) {
		res.send({ message: "添加失败,昵称和用户id不能为空", code: 201 })
	} else {

		// SQL语句
		var sql = "INSERT adds (aPhone,aDsser,aDs,aName,aUid) VALUES (?,?,?,?,?)";
		// 修改
		pool1.query(sql, [aPhone, aDsser, aDs, aName, aUid], (error, results) => {
			if (error) {

				next(error)

			}
			console.log(results)
			if (results.affectedRows > 0) {
				res.send({ message: "收货信息添加成功", code: 200 })
			}
		})
	}


})

// 8.四六级词汇
r.get('/words', (req, res, next) => {

	// SQL语句 words库 cet表
	let sql = 'select * from cet';

	pool2.query(sql, (error, results) => {

		if (error) {

			next(error);

			return
		}

		if (results.length == 0) {

			res.send({ message: '路由错误', code: 201 })
		} else {
			res.send({
				message: '查询成功', code: 200, result: results
			})
		}
	})
});

// 9.四六级真题
r.get('/46zt', (req, res, next) => {

	// SQL语句 46zt库 zt表
	let sql = 'SELECT * FROM zt';

	pool3.query(sql, (error, results) => {

		if (error) {

			next(error);

			return
		}

		if (results.length == 0) {

			res.send({ message: '路由错误', code: 201 })
		} else {
			res.send({
				message: '查询成功', code: 200, result: results
			})
		}
	})
});


// 10.首页 添加收藏接口
r.post('/addct', (req, res, next) => {

	//获取用户id kc库 vuex或props
	let o_uid = req.body.uId;

	//获取课程id kc库 首页课程请教
	let o_cid = req.body.cId;

	console.log(o_uid,o_cid);

	//SQL语句 kc库 ollect表
	var sql = 'SELECT o_cid FROM ollect where o_uid = ?';

	//操作数据库kc
	pool1.query(sql, [o_uid], (error, results) => {

		console.log(results)
		if (error) {

			next(error);

			return
		};
		results.forEach((item) => {
			console.log('课程' + item.o_cid + '已被被收藏')
		});
		// 查到已收藏的课程id
		if (results.length != 0) {

			let count = 0;

			results.forEach(function (item, i, arr) {

				if (item.o_cid == o_cid) count++

			});

			if (count > 0) {
				res.send({ code: 201, message: '已收藏过了' });
			} else {
				// 课程id添加到ollect
				let sql = 'INSERT INTO ollect (o_uid,o_cid) VALUES (?,?)';

				pool1.query(sql, [o_uid, o_cid], (error, results) => {

					if (error) {

						next(error);

						return
					};

					if (results.affectedRows > 0) {

						res.send({ code: 200, message: '收藏成功', result: { 'course_id': o_cid } })
					}
				})
			}

		}else {
			// 课程id添加到ollect
			let sql = 'INSERT INTO ollect (o_uid,o_cid) VALUES (?,?)';

			pool1.query(sql, [o_uid, o_cid], (error, results) => {

				if (error) {

					next(error);

					return
				};

				if (results.affectedRows > 0) {

					res.send({ code: 200, message: '收藏成功', result: { 'course_id': o_cid } })
				}
			})
		}


	})


});

// 取消收藏课程接口
r.post('/delct', (req, res, next) => {
	let cId = req.body.cId;
	let uId = req.body.uId;
	//SQL语句 
	let sql = 'delete from ollect where o_cId=? and o_uId=?'

	pool1.query(sql, [cId, uId], (error, results) => {

		if (error) {

			next(error);

			return
		}

		if (results.affectedRows > 0) {
			res.send({ message: '已经取消收藏', code: 200 })
		} else {
			res.send({ message: '取消失败', code: 201 })
		}
	})
})


// 11.我的课程页面 获取收藏接口
r.post('/getct', (req, res, next) => {

	//获取用户id kc库 user表
	let o_uid = req.body.uId;

	//SQL语句 kc库 ollect表
	var sql = 'SELECT o_cid FROM ollect where o_uid = ?';

	//操作数据库kc
	pool1.query(sql, [o_uid], (error, results) => {

		if (error) {

			next(error);

			return
		};

		if (results.length == 0) {
			res.send({ code: 201, message: '收藏夹为空' })
		} else {

			//拿到o_cid数组
			var arr = results.map(function (item, i, arr) {

				return item.o_cid

			});

			console.log(`收藏的课程cId有[${arr}]`);
			//sql语句 kc库 course表
			var sql = 'SELECT * FROM course where cId in (?)';

			//查询用户收藏了哪些课程
			pool1.query(sql, [arr], (error, results) => {

				if (error) {

					next(error);

					return
				};
				// arr不为空就一定有
				res.send({ code: 200, message: `找到${results.length}条收藏`, result: results })

			})
		}

	})


});

//12.词汇模糊查询接口
r.get('/getwords', (req, res, next) => {

	//获取单词
	let words = req.query.words;

	//模糊格式

	let mwords = `%${words}%`;

	//SQL语句
	let sql = 'SELECT * FROM cet where english like ? or chinese like ? or level like ?';

	//words库 cet表
	pool2.query(sql, [mwords, mwords, mwords], (error, results) => {

		if (error) next(error);

		if (results.length == 0) {
			res.send({ code: 201, message: '未找到' })
		} else {
			res.send({
				code: 200, message: `找到${results.length}个词汇`, result: results
			})
		}

	})
})



module.exports = r;